雙向佇列是一種具有佇列和堆疊兩種特性的資料結構。在雙向佇列中,我們可以從兩端(即前端和後端)插入和刪除元素。這使得雙向佇列比一般的佇列和堆疊更為靈活。
雙向佇列的特性
使用陣列實作雙向佇列
以下是雙向佇列的基本結構和操作:
#include <iostream>
#define SIZE 10
class Deque {
private:
int arr[SIZE];
int front;
int rear;
int size;
public:
Deque(int size) : front(-1), rear(0), size(size) {}
bool isFull() {
return ((front == 0 && rear == size - 1) || front == rear + 1);
}
bool isEmpty() {
return (front == -1);
}
void insertFront(int key) {
if (isFull()) {
std::cout << "Deque is full" << std::endl;
return;
}
if (front == -1) {
front = rear = 0;
} else if (front == 0) {
front = size - 1;
} else {
front = front - 1;
}
arr[front] = key;
}
void insertRear(int key) {
if (isFull()) {
std::cout << "Deque is full" << std::endl;
return;
}
if (front == -1) {
front = rear = 0;
} else if (rear == size - 1) {
rear = 0;
} else {
rear = rear + 1;
}
arr[rear] = key;
}
void deleteFront() {
if (isEmpty()) {
std::cout << "Deque is empty" << std::endl;
return;
}
if (front == rear) {
front = rear = -1;
} else if (front == size - 1) {
front = 0;
} else {
front = front + 1;
}
}
void deleteRear() {
if (isEmpty()) {
std::cout << "Deque is empty" << std::endl;
return;
}
if (front == rear) {
front = rear = -1;
} else if (rear == 0) {
rear = size - 1;
} else {
rear = rear - 1;
}
}
int getFront() {
if (isEmpty()) {
std::cout << "Deque is empty" << std::endl;
return -1;
}
return arr[front];
}
int getRear() {
if (isEmpty() || rear < 0) {
std::cout << "Deque is empty" << std::endl;
return -1;
}
return arr[rear];
}
};
int main() {
Deque dq(5);
dq.insertFront(1);
dq.insertRear(2);
dq.insertFront(3);
dq.insertRear(4);
std::cout << "Front element: " << dq.getFront() << std::endl;
std::cout << "Rear element: " << dq.getRear() << std::endl;
return 0;
}
總結
雙向佇列是一個非常靈活的資料結構,它允許我們在佇列的兩端進行操作。這在某些算法和問題中可能非常有用,特別是當我們需要同時具有佇列和堆疊的特性時。